package com.zhdl.modules.process.task;

import com.zhdl.common.conf.TaskSchedulerConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;

import java.util.concurrent.ScheduledFuture;
@Slf4j
@Component
public class DynamicTask{
    @Autowired
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;

    public void startTask(CustomizeTask task, int time){
        ScheduledFuture<?> scheduledFuture = threadPoolTaskScheduler.scheduleWithFixedDelay(task, time);
        TaskSchedulerConfig.cache.put(task.getName(),scheduledFuture);
    }

    public void stopTaskById(String taskId){
        if (TaskSchedulerConfig.cache.isEmpty()) return;
        if (TaskSchedulerConfig.cache.get(taskId) == null) return;
        ScheduledFuture scheduledFuture = TaskSchedulerConfig.cache.get(taskId);
        if (scheduledFuture != null) {
            scheduledFuture.cancel(true);   // 这里需要使用指定的 scheduledFuture 来停止当前的线程
            TaskSchedulerConfig.cache.remove(taskId);        // 移除缓存
        }
    }

    public void stopAll(){
        if (TaskSchedulerConfig.cache.isEmpty()) return;
        TaskSchedulerConfig.cache.values().forEach(scheduledFuture -> scheduledFuture.cancel(true));
        TaskSchedulerConfig.cache.clear();
    }
    public void testNext(Integer process){
        log.info("testNext当前进度{}",process);
    }
}
